<!DOCTYPE html>
<html lang="en">

<head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="node_modules/.3.1.1@jquery/dist/jquery.min.js"></script>
    <script src="node_modules/.1.4.1@jquery.cookie/jquery.cookie.js"></script>
</head>

<body>
    <div id="msgshwo">
    </div>
    <div>
    <input type="text" id="msg" /> <input type="button" id="sendbtn" value="发送" />
    </div>
    <script>
        $(function() {

            var uid = $.cookie("uid");
            var wsurl = "ws://127.0.0.1:8001/?";
            if (uid) {
                wsurl += "uid=" + uid;
            }
            var ws = new WebSocket(wsurl);
            ws.onopen = function() {
                showmsg("open...");
            }
            ws.onmessage = function(msg) {
            	console.log(msg)
                showmsg(msg.data);
                var jdata = JSON.parse(msg.data);
                switch (jdata.type) {
                    case "C":
                        $.cookie("uid", jdata.uid);
                        break;
                }


            }
            ws.onclose = function() {
                showmsg("close...");
            }
            ws.onerror = function(log) {
                console.log(log);
                showmsg(log.type + ":" + log.target.readyState);
            }
            
            window.onunload=function(){
            	ws.close();
            }
            $("#sendbtn").click(function(){
            	var str=JSON.stringify({type:'TXT',msg:$("#msg").val()});
            	console.log(str);
            	ws.send(str)
            })
        });

        function showmsg(msg) {
            $("#msgshwo").append("<p>" + msg + "</p>");
        }
        
    </script>
</body>

</html>